// 分析服务命令
use serde::{Deserialize, Serialize};
use tauri::command;


use crate::error::AppError;
use crate::services::analytics::{AnalyticsService, AnalysisRequest, AnalysisResult, AnalysisType, AnalysisOptions};
use crate::services::manager::get_service_manager;

// 全局分析服务实例
lazy_static::lazy_static! {
    static ref ANALYTICS_SERVICE: AnalyticsService = AnalyticsService::new();
}

/// 详细项目分析命令
#[command]
pub async fn analyze_project_detailed(
    project_path: String,
    analysis_types: Vec<String>,
    options: Option<AnalysisOptionsInput>,
) -> Result<AnalysisResult, AppError> {
    // 确保服务已初始化
    if let Err(_) = ANALYTICS_SERVICE.initialize().await {
        ANALYTICS_SERVICE.initialize().await?;
    }

    // 转换分析类型
    let analysis_types: Vec<AnalysisType> = analysis_types
        .into_iter()
        .map(|t| match t.as_str() {
            "complexity" => AnalysisType::Complexity,
            "quality" => AnalysisType::Quality,
            "trends" => AnalysisType::Trends,
            "all" => AnalysisType::All,
            _ => AnalysisType::All,
        })
        .collect();

    let request = AnalysisRequest {
        project_path,
        analysis_types,
        options: options.map(|o| o.into()).unwrap_or_default(),
    };

    // 获取图系统引用
    let service_manager = get_service_manager();
    let graph_system = service_manager.get_graph_system();

    ANALYTICS_SERVICE.analyze_project(request, graph_system).await
}

/// 获取项目统计信息
#[command]
pub async fn get_project_stats() -> Result<ProjectStatsResponse, AppError> {
    // 模拟项目统计数据
    Ok(ProjectStatsResponse {
        total_files: 156,
        total_lines: 12543,
        languages: vec![
            LanguageStats { name: "TypeScript".to_string(), percentage: 45.0, files: 70 },
            LanguageStats { name: "Rust".to_string(), percentage: 30.0, files: 47 },
            LanguageStats { name: "JavaScript".to_string(), percentage: 15.0, files: 23 },
            LanguageStats { name: "CSS".to_string(), percentage: 10.0, files: 16 },
        ],
        last_analyzed: chrono::Utc::now(),
    })
}

/// 获取最近活动
#[command]
pub async fn get_recent_activity() -> Result<Vec<ActivityItem>, AppError> {
    // 模拟最近活动数据
    Ok(vec![
        ActivityItem {
            id: "1".to_string(),
            activity_type: "file_opened".to_string(),
            description: "打开文件 App.tsx".to_string(),
            timestamp: chrono::Utc::now() - chrono::Duration::minutes(5),
        },
        ActivityItem {
            id: "2".to_string(),
            activity_type: "file_saved".to_string(),
            description: "保存文件 router.ts".to_string(),
            timestamp: chrono::Utc::now() - chrono::Duration::minutes(10),
        },
        ActivityItem {
            id: "3".to_string(),
            activity_type: "analysis_completed".to_string(),
            description: "代码分析完成".to_string(),
            timestamp: chrono::Utc::now() - chrono::Duration::minutes(30),
        },
    ])
}

/// 获取代码图谱数据
#[command]
pub async fn get_code_graph() -> Result<CodeGraphResponse, AppError> {
    // 模拟代码图谱数据
    Ok(CodeGraphResponse {
        nodes: vec![
            GraphNode {
                id: "app".to_string(),
                label: "App.tsx".to_string(),
                node_type: "file".to_string(),
                size: 20,
                color: "#3b82f6".to_string(),
            },
            GraphNode {
                id: "router".to_string(),
                label: "Router.tsx".to_string(),
                node_type: "file".to_string(),
                size: 15,
                color: "#3b82f6".to_string(),
            },
            GraphNode {
                id: "store".to_string(),
                label: "Store.ts".to_string(),
                node_type: "file".to_string(),
                size: 18,
                color: "#10b981".to_string(),
            },
        ],
        edges: vec![
            GraphEdge {
                id: "e1".to_string(),
                source: "app".to_string(),
                target: "router".to_string(),
                edge_type: "imports".to_string(),
                weight: 1,
            },
            GraphEdge {
                id: "e2".to_string(),
                source: "app".to_string(),
                target: "store".to_string(),
                edge_type: "imports".to_string(),
                weight: 1,
            },
        ],
    })
}

// 数据结构定义

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalysisOptionsInput {
    pub include_tests: Option<bool>,
    pub include_dependencies: Option<bool>,
    pub max_depth: Option<u32>,
    pub file_patterns: Option<Vec<String>>,
}

impl Into<AnalysisOptions> for AnalysisOptionsInput {
    fn into(self) -> AnalysisOptions {
        AnalysisOptions {
            include_tests: self.include_tests.unwrap_or(true),
            include_dependencies: self.include_dependencies.unwrap_or(false),
            max_depth: self.max_depth,
            file_patterns: self.file_patterns.unwrap_or_else(|| {
                vec!["**/*.rs".to_string(), "**/*.ts".to_string(), "**/*.js".to_string()]
            }),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectStatsResponse {
    pub total_files: u32,
    pub total_lines: u32,
    pub languages: Vec<LanguageStats>,
    pub last_analyzed: chrono::DateTime<chrono::Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LanguageStats {
    pub name: String,
    pub percentage: f64,
    pub files: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActivityItem {
    pub id: String,
    pub activity_type: String,
    pub description: String,
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodeGraphResponse {
    pub nodes: Vec<GraphNode>,
    pub edges: Vec<GraphEdge>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphNode {
    pub id: String,
    pub label: String,
    pub node_type: String,
    pub size: u32,
    pub color: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphEdge {
    pub id: String,
    pub source: String,
    pub target: String,
    pub edge_type: String,
    pub weight: u32,
}
